package com.lhkj.ct.meta.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lhkj.ct.base.constants.SystemConstants;
import com.lhkj.ct.base.enums.DeleteStatus;
import com.lhkj.ct.base.enums.GlobalStatus;
import com.lhkj.ct.base.enums.ReturnStatus;
import com.lhkj.ct.base.exception.BusinessException;
import com.lhkj.ct.base.model.Option;
import com.lhkj.ct.base.model.dto.PageQuery;
import com.lhkj.ct.base.mybatis.extension.service.impl.IServiceImpl;
import com.lhkj.ct.base.utils.OptionUtil;
import com.lhkj.ct.base.utils.TreeUtil;
import com.lhkj.ct.meta.admin.converter.FormConverter;
import com.lhkj.ct.meta.admin.mapper.SysOrganMapper;
import com.lhkj.ct.meta.admin.model.dto.OrganForm;
import com.lhkj.ct.meta.admin.model.entity.TblOrgan;
import com.lhkj.ct.meta.admin.model.vo.OrganTreeVo;
import com.lhkj.ct.meta.admin.service.SysOrganService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 机构表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2023-09-12
 */
@Service
public class SysOrganServiceImpl extends IServiceImpl<SysOrganMapper, TblOrgan> implements SysOrganService {

    @Override
    public List<OrganTreeVo> listOrgans(TblOrgan organ, PageQuery pageQuery) {
        LambdaQueryWrapper<TblOrgan> wrapper = new LambdaQueryWrapper<TblOrgan>()
                .select(TblOrgan::getId, TblOrgan::getParentId, TblOrgan::getOrganCode, TblOrgan::getOrganName, TblOrgan::getStatus, TblOrgan::getSort)
                .like(StringUtils.isNotBlank(organ.getOrganName()), TblOrgan::getOrganName, organ.getOrganName())
                .eq(Objects.nonNull(organ.getStatus()), TblOrgan::getStatus, organ.getStatus());
        List<OrganTreeVo> organTreeVos = this.getBaseMapper().listOrgans(wrapper);
        return TreeUtil.builderTree(organTreeVos);
    }

    @Override
    public List<Option<String>> listOptions() {
        LambdaQueryWrapper<TblOrgan> wrapper = new LambdaQueryWrapper<TblOrgan>()
                .select(TblOrgan::getId, TblOrgan::getParentId, TblOrgan::getOrganName)
                .eq( TblOrgan::getStatus, GlobalStatus.NORMAL.getValue())
                .orderByAsc(TblOrgan::getSort);
        List<TblOrgan> organTreeVos = this.getBaseMapper().selectList( wrapper);
        return OptionUtil.buildTreeOption(organTreeVos, TblOrgan::getOrganName);
    }

    @Override
    public int saveOrgan(OrganForm organForm) {
        TblOrgan tblOrgan = FormConverter.INSTANCE.convertForm2Role(organForm);
        String treePath = generateDeptTreePath(tblOrgan.getParentId());
        tblOrgan.setTreePath(treePath);
        if (!checkCodeUnique(tblOrgan)){
            throw new BusinessException(ReturnStatus.LOGICAL_VALIDATE_FAILED, "机构编码已存在");
        }
        return saveOrUpdate(tblOrgan);
    }

    @Override
    public boolean checkCodeUnique(TblOrgan tblOrgan) {
        TblOrgan target = getBaseMapper().selectOne(
                new LambdaUpdateWrapper<TblOrgan>()
                        .eq(TblOrgan::getOrganCode, tblOrgan.getOrganCode())
                        .last("limit 1")
        );
        return (null == target || target.getId().equals(tblOrgan.getId()));
    }

    @Override
    public int removeByIds(Collection<? extends Serializable> idList) {
//        for (Serializable id : idList) {
//            Asserts.assertFalse(hasChildOrgan((String) id), "存在下级机构,不允许删除");
//            Asserts.assertFalse(hasDept((String) id), "存在下级部门,不允许删除");
//        }
        return getBaseMapper().deleteBatchIds(idList);
    }

    @Override
    public boolean hasChildOrgan(String organId) {
        Long count = getBaseMapper().selectCount(
                new LambdaQueryWrapper<TblOrgan>()
                        .select(TblOrgan::getId)
                        .eq(TblOrgan::getParentId, organId)
                        .eq(TblOrgan::getDelFlag, DeleteStatus.NORMAL));
        return count > 0;
    }

    @Override
    public boolean hasDept(String organId) {
        return getBaseMapper().hasDept(organId) > 0;
    }

    /**
     * 部门路径生成
     *
     * @param parentId 父ID
     * @return 父节点路径以英文逗号(, )分割，eg: 1,2,3
     */
    private String generateDeptTreePath(String parentId) {
        String treePath = null;
        if (SystemConstants.ROOT_NODE_ID.equals(parentId)) {
            treePath = parentId;
        } else {
            TblOrgan parent = this.getById(parentId);
            if (parent != null) {
                treePath = parent.getTreePath() + "," + parent.getId();
            }
        }
        return treePath;
    }
}
